/*
 *  (c) 2005 Zhijie Chen <zigzag.chen@gmail.com>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *	  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var JSTemplate = {
	process: function(template,context) {
		var parseResult;
		var functionText=["var tempFunction=function(context,stack) { with (context) {"];
		functionText.push("out=[];");
		var lines = template.split('\n');
		for (var i = 0; i < lines.length; i++) {
			this._parseLine(lines[i], functionText);
		}
		functionText.push("return out.join(\"\\n\");");
		functionText.push("}}");
		try {
			eval(functionText.join(""));
		} catch (e) {
			alert(functionText.join("\n"));
			alert("eval ERROR("+ e.toString()+"). Check for unclosed, unmatched statement(s).");
			return;
		}

		var stack=[];
		try {
			parseResult = tempFunction(context,stack);
		} catch (e) {
			alert("ERROR("+e.toString()+") at \""+stack[stack.length-1]+"\"");
		}
		return parseResult;
	},

	_parseLine:function(line,functionText) {
		var escaped=line.replace("\r","");
		escaped=escaped.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
		escaped=escaped.replace(/<!--begin/g,"<!--begin-->").replace(/end-->/g,"<!--end-->");
		var prefix;
		if (line.charAt(0)=='#') {
			prefix="stack.push(\""+escaped.replace(/\"/g,"\\\"")+ "\");\n";
			functionText.push(prefix+escaped.substring(1,escaped.length));
		} else {
			escaped=escaped.replace(/\"/g,"\\\"").replace(/@\{/g,"\"+").replace(/\}/g,"+\"");
			prefix="stack.push(\""+escaped+ "\");\n";
			functionText.push(prefix+"out.push(\""+escaped+"\");");
		}
	}
};